package com.ucap.weking.guangan.Activitys;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.ucap.weking.guangan.R;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class NewContentActivity extends AppCompatActivity {

    @InjectView(R.id.activity_new_content)
    CoordinatorLayout clContent;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.wb_content)
    WebView wbContent;
    @InjectView(R.id.pb_loading)
    ProgressBar pbLoading;
    ArrayList<String> imageUri;
    private String uri;

    public static void startThisActivity(Context ctx, String title, String uri) {
        Intent intent = new Intent(ctx, NewContentActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("uri", uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
        setContentView(R.layout.activity_new_content);
        ButterKnife.inject(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        uri = intent.getStringExtra("uri");
        actionBar.setTitle(title);
        setData(uri);
    }

    public void setData(final String uri) {
        WebSettings webSettings = wbContent.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);//关键点
        wbContent.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//缓存模式，（不使用本地缓存）
        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        // 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
        //扩大比例的缩放
        webSettings.setLoadWithOverviewMode(true);
//        webSettings.set
        wbContent.setWebViewClient(new WebViewClient() {
            //网页开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i("pathUri", url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                wbContent.loadUrl("javascript:(function(){"
                        + "var objs=document.getElementsByTagName(\"img\");"
                        + "for(var i=0;i<objs.length;i++){"
                        + "     window.imagelistner.imagsUrl(objs[i].src);"
                        + "      objs[i].onclick=function(){"
                        + "          window.imagelistner.openImage(this.src)"
                        + " }"
                        + "}"
                        + "})()");
            }
        });
        wbContent.setVisibility(View.INVISIBLE);
        wbContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pbLoading.setVisibility(View.GONE);
                    wbContent.setVisibility(View.VISIBLE);
                }

            }


        });
        wbContent.loadUrl(uri);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.menu_share:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/*");
                intent.putExtra(Intent.EXTRA_SUBJECT, "中国广安");
                intent.putExtra(Intent.EXTRA_TEXT, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, getTitle()));
                break;

        }
        return true;
    }

    //js注入接口定义,方法名对应js方法名(解析后自动调用)
    private class JavascriptInterface {
        public JavascriptInterface(Context context) {

        }

        @android.webkit.JavascriptInterface
        public void openImage(final String img) {
            Log.i("image", "img" + img);
            if (imageUri != null) {
            }
        }

        @android.webkit.JavascriptInterface
        public void imagsUrl(String img) {
            if (imageUri == null) {
                imageUri = new ArrayList<>();
            }
            imageUri.add(img);
        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && wbContent.canGoBack()) {
            wbContent.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        wbContent.loadUrl(uri);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (wbContent != null) {//完全移除webView
            wbContent.setVisibility(View.GONE);
            wbContent.removeAllViews();
            wbContent.destroy();
            clContent.removeView(wbContent);
        }
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void finish() {
        //防止webView出现
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }
}
